package com.melody.android.logic

import android.media.AudioAttributes
import android.media.MediaPlayer
import com.melody.android.logic.util.songSource

/**
 * 音乐播放器管理类
 */
class MediaPlayerManager private constructor() {

    private val mediaPlayer: MediaPlayer = MediaPlayer()
    var isPlaying: Boolean = false
        private set

    fun setDataSource(songName: String) {
        // 从云服务器获取音乐资源并做好播放准备
        val audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .build()
        mediaPlayer.setAudioAttributes(audioAttributes)
        mediaPlayer.setDataSource(songSource[songName])
        mediaPlayer.prepare()
    }

    /**
     * 开始播放
     */
    fun play() {
        mediaPlayer.start()
        isPlaying = true
    }

    /**
     * 暂停播放
     */
    fun pause() {
        mediaPlayer.pause()
        isPlaying = false
    }

    /**
     * 停止播放
     */
    fun stop() {
        mediaPlayer.stop()
        mediaPlayer.reset()     // 重置状态
        isPlaying = false
    }

    /**
     * 获取媒体播放器的播放时长
     */
    fun getMediaPlayerDuration(): Int {
        return mediaPlayer.duration
    }

    /**
     * 设置媒体播放器的播放进度
     */
    fun seekTo(progress: Int) {
        mediaPlayer.seekTo(progress)
    }

    /**
     * 获取媒体播放器当前的播放位置
     */
    fun getMediaPlayerCurrentPosition(): Int {
        return mediaPlayer.currentPosition
    }

    /**
     * MediaPlayerManager伴生对象 单例模式
     */
    companion object {
        private var instance: MediaPlayerManager? = null

        fun getInstance(): MediaPlayerManager {
            if (instance == null) {
                instance = MediaPlayerManager()
            }
            return instance!!
        }
    }

}